package org.jeecg.modules.kaoqtjMx.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.kaoqgz.service.IAgKaoqgzService;
import org.jeecg.modules.kaoqtj.entity.AgKaoqtj;
import org.jeecg.modules.kaoqtj.service.IAgKaoqtjService;
import org.jeecg.modules.kaoqtjMx.entity.AgKaoqtjMx;
import org.jeecg.modules.kaoqtjMx.service.IAgKaoqtjMxService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.tongxjl.entity.AgTongxjl;
import org.jeecg.modules.tongxjl.service.IAgTongxjlService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 考勤统计明细
 * @Author: jeecg-boot
 * @Date:   2020-10-13
 * @Version: V1.0
 */
@Api(tags="考勤统计明细")
@RestController
@RequestMapping("/kaoqtjMx/agKaoqtjMx")
@Slf4j
public class AgKaoqtjMxController extends JeecgController<AgKaoqtjMx, IAgKaoqtjMxService> {
	@Autowired
	private IAgKaoqtjMxService agKaoqtjMxService;

	 @Autowired
	 private IAgTongxjlService agTongxjlService;

	 @Autowired
	 private IAgKaoqgzService agKaoqgzService;

	 @Autowired
	 private IAgKaoqtjService agKaoqtjService;

	 List<String> middleDays(String startday, String endday) {
		 List<String> daysarr = new ArrayList<>();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		 try {
			 Calendar cld = Calendar.getInstance();
			 cld.setTime(sdf.parse(endday));
			 cld.add(Calendar.DAY_OF_MONTH, 1);
			 Date enddate = cld.getTime();
			 Date temp = sdf.parse(startday);
			 int onedaylength = 86400000;

			 while (temp.before(enddate)) {
				 daysarr.add(sdf.format(temp));
				 long timestamp = temp.getTime();
				 timestamp += onedaylength;
				 temp = new Date(timestamp);
			 }

		 } catch (Exception e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
		 }

		 return daysarr;
	 }

	 //获取当前月第一天
	 public   static   Date   getFirstDayOfMonth(Date   someDate)   {
		 Calendar ca = Calendar.getInstance();
		 ca.setTime(someDate); //
		 ca.set(Calendar.DAY_OF_MONTH, 1);
		 Date firstDate = ca.getTime();
		 ca.add(Calendar.MONTH, 1);
		 ca.add(Calendar.DAY_OF_MONTH, -1);
		 Date lastDate = ca.getTime();
		 return firstDate;
	 }
	/**
	 * 分页列表查询
	 *
	 * @param //agKaoqtjMx
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-分页列表查询")
	@ApiOperation(value="考勤统计明细-分页列表查询", notes="考勤统计明细-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AgTongxjl agTongxjl,
	//public Result<?> queryPageList(AgKaoqtj agKaoqtj,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		List<AgKaoqtjMx> result = new ArrayList<>();


		String tongxsj_begin = req.getParameter("tongxsj_begin");
		 //tongxsj_begin ="2020-10-26 00:00:00";
		String tongxsj_end = req.getParameter("tongxsj_end");
		 //tongxsj_end ="2020-10-26 23:59:00" ;

		if (tongxsj_begin == null || tongxsj_end == null||tongxsj_begin =="" || tongxsj_end == "") {
			String today = DateUtils.formatDate(new Date());
			tongxsj_begin =DateUtils.formatDate(getFirstDayOfMonth(new Date()));
			tongxsj_end = today;
		}

		AgKaoqtj agKaoqtj = new AgKaoqtj();
		agKaoqtj.setRenybh(agTongxjl.getShibzp());
		//agKaoqtj.setRenybh(agTongxjl.getRenybh());

		QueryWrapper<AgKaoqtj> queryWrapper = QueryGenerator.initQueryWrapper(agKaoqtj, req.getParameterMap());
		List<AgKaoqtj> list = agKaoqtjService.list(queryWrapper);

		List<String> day_of_month = middleDays(tongxsj_begin, tongxsj_end);
		for (String today : day_of_month
		) {
			List<AgKaoqtj> list2 = list.stream()
					.filter(p -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(p.getShangbsj()).startsWith(today))
					.sorted(Comparator.comparing(AgKaoqtj::getShangbsj))
					.collect(Collectors.toList());
			if(list2.size() == 0)
				continue;

			AgKaoqtjMx agKaoqtjMx = new AgKaoqtjMx();
			agKaoqtjMx.setId(UUID.randomUUID().toString().replace("-", ""));
			AgKaoqtj tmp = list2.get(0);
			agKaoqtjMx.setXingm(tmp.getXingm());
			agKaoqtjMx.setBum(tmp.getBum());

			Date shangb = list2.get(0).getShangbsj();
			agKaoqtjMx.setRiq(new SimpleDateFormat("yyyy-MM-dd").format(shangb));
			//System.out.println("上班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(shangb));
			agKaoqtjMx.setShoucdk(new SimpleDateFormat("HH:mm:ss").format(shangb));

			Date xiab = list2.get(0).getXiabsj();
			//System.out.println("下班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(xiab));
			agKaoqtjMx.setMocdk(new SimpleDateFormat("HH:mm:ss").format(xiab));
			long gongs = xiab.getTime() - shangb.getTime();
			long hour = gongs / 1000 / (60 * 60);
			long minute = gongs / 1000 / (60 * 60);

			agKaoqtjMx.setGongs(hour + "." + minute);

			if (list2.size() > 1) {
				 xiab = list2.get(list2.size() - 1).getXiabsj();
				//System.out.println("下班时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(xiab));
				agKaoqtjMx.setMocdk(new SimpleDateFormat("HH:mm:ss").format(xiab));
				gongs = xiab.getTime() - shangb.getTime();
				hour = gongs / 1000 / (60 * 60);
				minute = gongs / 1000 / (60 * 60);

				agKaoqtjMx.setGongs(hour + "." + minute);
			}

			result.add(agKaoqtjMx);
		}

		IPage<AgKaoqtjMx> pageList = new Page<>(pageNo, pageSize);
		pageList.setRecords(result);

		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param agKaoqtjMx
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-添加")
	@ApiOperation(value="考勤统计明细-添加", notes="考勤统计明细-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AgKaoqtjMx agKaoqtjMx) {
		agKaoqtjMxService.save(agKaoqtjMx);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param agKaoqtjMx
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-编辑")
	@ApiOperation(value="考勤统计明细-编辑", notes="考勤统计明细-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AgKaoqtjMx agKaoqtjMx) {
		agKaoqtjMxService.updateById(agKaoqtjMx);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-通过id删除")
	@ApiOperation(value="考勤统计明细-通过id删除", notes="考勤统计明细-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		agKaoqtjMxService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-批量删除")
	@ApiOperation(value="考勤统计明细-批量删除", notes="考勤统计明细-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.agKaoqtjMxService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "考勤统计明细-通过id查询")
	@ApiOperation(value="考勤统计明细-通过id查询", notes="考勤统计明细-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AgKaoqtjMx agKaoqtjMx = agKaoqtjMxService.getById(id);
		if(agKaoqtjMx==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(agKaoqtjMx);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param agKaoqtjMx
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AgKaoqtjMx agKaoqtjMx) {
        return super.exportXls(request, agKaoqtjMx, AgKaoqtjMx.class, "考勤统计明细");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AgKaoqtjMx.class);
    }

}
